import {debounce} from 'lodash';
import {memStore} from "../../../Store/memStore";
import request from '../../../utils/request.js';
import { messageToast } from '@components/common/MessageToast/scripts.js';

// 显示消息提示的工具函数
function showMessage(shadowRoot, message, variant = 'primary', duration = 5000) {
    const alert = shadowRoot.getElementById('messageAlert');
    const messageText = shadowRoot.getElementById('messageText');
    const icon = alert.querySelector('sl-icon[slot="icon"]');
    
    if (!alert || !messageText || !icon) return;
    
    // 设置消息内容
    messageText.textContent = message;
    
    // 设置样式和图标
    alert.variant = variant;
    switch (variant) {
        case 'success':
            icon.name = 'check-circle';
            break;
        case 'warning':
            icon.name = 'exclamation-triangle';
            break;
        case 'danger':
            icon.name = 'exclamation-octagon';
            break;
        default:
            icon.name = 'info-circle';
    }
    
    // 显示alert
    alert.show();
    
    // 自动隐藏
    if (duration > 0) {
        setTimeout(() => {
            alert.hide();
        }, duration);
    }
}

export function bindEvents(shadowRoot, component) {
    const closeBtn = shadowRoot.getElementById('closeBtn');
    const registerForm = shadowRoot.getElementById('registerForm');
    const sendCodeBtn = shadowRoot.getElementById('sendCodeBtn');
    const loginLink = shadowRoot.getElementById('loginLink');

    // 关闭按钮事件
    closeBtn.addEventListener('click', () => {
        component.closeModal();
    });

    // 表单提交事件
    registerForm.addEventListener('submit', (e) => {
        e.preventDefault();
        if (!component.isLoading) {
            component.handleRegister();
        }
    });

    // 发送验证码事件
    sendCodeBtn.addEventListener('click', () => {
        if (!component.isLoading) {
            component.handleSendCode();
        }
    });

    // 登录链接事件
    loginLink.addEventListener('click', (e) => {
        e.preventDefault();
        component.handleLoginLink();
    });


    // 实时验证
    const emailInput = shadowRoot.getElementById('registerEmail');
        const passwordInput = shadowRoot.getElementById('registerPassword');
    
    const debouncedEmailValidation = debounce(async () => await component.validateEmail(), 300);
    const debouncedPasswordValidation = debounce(() => component.validatePassword(), 300);
    
    emailInput.addEventListener('input', debouncedEmailValidation);
    passwordInput.addEventListener('input', debouncedPasswordValidation);
}

export function openModal(shadowRoot) {
    const modal = shadowRoot.getElementById('registerModal');
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    
    // 添加动画类
    setTimeout(() => {
        modal.classList.add('show');
    }, 10);
}

export function closeModal(shadowRoot) {
    const modal = shadowRoot.getElementById('registerModal');
    modal.classList.remove('show');
    
    setTimeout(() => {
        modal.style.display = 'none';
        document.body.style.overflow = '';
    }, 300);
}

export async function handleRegister(shadowRoot, component) {
    if (!component.validateForm()) {
        return;
    }

    const emailElement = shadowRoot.getElementById('registerEmail');
        const passwordElement = shadowRoot.getElementById('registerPassword');
        const confirmPasswordElement = shadowRoot.getElementById('registerConfirmPassword');
        const verificationCodeElement = shadowRoot.getElementById('registerVerificationCode');

    const email = emailElement.value;
    const password = passwordElement.value;
    const confirmPassword = confirmPasswordElement.value;
    const verificationCode = verificationCodeElement.value;



    try {
        component.setLoading(true);
        const userData = await component.simulateRegister(email, password, confirmPassword, verificationCode);
        component.handleRegisterSuccess(userData);
    } catch (error) {
        component.handleRegisterError(error.message);
    } finally {
        component.setLoading(false);
    }
}

export async function simulateRegister(email, password, confirmPassword, verificationCode) {
    // 前端验证
    if (!email || !password || !confirmPassword || !verificationCode) {
        throw new Error('请填写所有必填字段');
    }

    if (password !== confirmPassword) {
        throw new Error('两次输入的密码不一致');
    }

    try {
        // 调用后端注册API
        const response = await request.post('/users/register/sign-up', {
            mail: email,
            code: verificationCode,
            pass: password,
            confirm: confirmPassword
        });

        // 注册成功 - request.js已经处理了业务状态码判断
        return {
            id: response.data.data.userId,
            email: response.data.data.email,
            username: response.data.data.username,
            nickname: response.data.data.nickname,
            avatar: response.data.data.avatar,
            createAt: response.data.data.createAt
        };
    } catch (error) {
        // request.js已经处理了错误信息，直接抛出
        throw error;
    }
}

export function handleRegisterSuccess(userData, shadowRoot, component) {
    // 存储用户数据到内存存储
    memStore.set('currentUser', userData);
    memStore.set('isLoggedIn', true);
    
    // 显示成功消息，5秒后自动关闭
    alert('注册成功！欢迎加入我们！');
    showMessage(shadowRoot, '注册成功！欢迎加入我们！', 'success', 5000);
    
    // 延迟关闭模态框（在消息显示5秒后）
    setTimeout(() => {
        component.closeModal();
        component.resetForm();
    }, 5500);
}

export function handleRegisterError(errorMessage, shadowRoot, component) {
    showMessage(shadowRoot, errorMessage, 'danger', 5000);
}

export async function handleSendCode(shadowRoot, component) {
    const emailInput = shadowRoot.getElementById('registerEmail');
    const sendCodeBtn = shadowRoot.getElementById('sendCodeBtn');
    const email = emailInput.value;

    // 验证邮箱
    if (!email) {
        component.showError(shadowRoot.getElementById('registerEmailError'), '请先输入邮箱地址');
        return;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        component.showError(shadowRoot.getElementById('registerEmailError'), '请输入有效的邮箱地址');
        return;
    }

    try {
        // 禁用按钮并显示倒计时
        sendCodeBtn.disabled = true;
        let countdown = 60;
        
        const updateButtonText = () => {
            sendCodeBtn.textContent = `${countdown}秒后重试`;
            countdown--;
            
            if (countdown < 0) {
                sendCodeBtn.disabled = false;
                sendCodeBtn.textContent = '发送验证码';
                return;
            }
            
            setTimeout(updateButtonText, 1000);
        };
        
        updateButtonText();

        // 调用后端发送验证码API
        const response = await request.post('/users/register/send-code', {
            mail: email
        });
        
        // 发送成功 - request.js已经处理了业务状态码判断
        showMessage(shadowRoot, response.data.message || '验证码已发送到您的邮箱', 'success', 3000);
        // 清除邮箱错误
        component.hideError(shadowRoot.getElementById('registerEmailError'));
        
    } catch (error) {
        // 网络错误或其他异常
        sendCodeBtn.disabled = false;
        sendCodeBtn.textContent = '发送验证码';
        
        // request.js已经处理了错误信息，直接使用error.message
        const errorMessage = error.message || '发送验证码失败，请重试';
        showMessage(shadowRoot, errorMessage, 'danger', 5000);
    }
}

export function handleLoginLink(component) {
    // 关闭注册模态框
    component.closeModal();
    
    // 查找或创建登录模态框
    let loginModal = document.querySelector('email-login');
    const app = document.getElementById('app');
    if (!loginModal) {
        // 如果不存在，创建新的登录组件
        loginModal = document.createElement('email-login');
        if (app) {
            app.appendChild(loginModal);
        } else {
            document.body.appendChild(loginModal);
        }
    }
    
    // 打开登录模态框
    loginModal.open();
    
    // 将注册的组件删除
    const registerElement = document.querySelector('email-register');
    if (registerElement && registerElement.parentNode) {
        registerElement.parentNode.removeChild(registerElement);
    }
}



export function validateForm(shadowRoot, component) {
    const email = shadowRoot.getElementById('registerEmail').value;
    const password = shadowRoot.getElementById('registerPassword').value;
    const confirmPassword = shadowRoot.getElementById('registerConfirmPassword').value;
    const verificationCode = shadowRoot.getElementById('registerVerificationCode').value;

    let isValid = true;

    // 清除之前的错误
    component.clearErrors();

    // 验证邮箱
    if (!email) {
        component.showError(shadowRoot.getElementById('registerEmailError'), '请输入邮箱地址');
        isValid = false;
    } else {
        const emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
        if (!emailRegex.test(email)) {
            component.showError(shadowRoot.getElementById('registerEmailError'), '邮箱格式不正确，请及时更正');
            isValid = false;
        }
    }

    // 验证验证码
    if (!verificationCode) {
        component.showError(shadowRoot.getElementById('registerVerificationCodeError'), '请输入验证码');
        isValid = false;
    }

    // 验证密码
    if (!password) {
        console.warn(shadowRoot);
        component.showError(shadowRoot.getElementById('registerPasswordError'), '请输入密码');
        isValid = false;
    } else {
        const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&.])[A-Za-z\d@$!%*#?&_.]{8,}$/;
        if (!passwordRegex.test(password)) {
            component.showError(shadowRoot.getElementById('registerPasswordError'), '密码至少8位，必须包含字母和数字,和@$!%*#?&_.');
            isValid = false;
        }
    }

    // 验证确认密码
    if (!confirmPassword) {
        component.showError(shadowRoot.getElementById('registerConfirmPasswordError'), '请确认密码');
        isValid = false;
    } else if (password !== confirmPassword) {
        component.showError(shadowRoot.getElementById('registerConfirmPasswordError'), '两次输入的密码不一致');
        isValid = false;
    }

    return isValid;
}

/**
 * 检测邮箱是否已经注册
 * @param {string} email - 邮箱地址
 * @returns {Promise<{exists: boolean, error?: string}>} - 返回检测结果和可能的错误信息
 */
export async function checkEmailExists(email) {
    try {
        const response = await request.post('/users/register/verify-mail', {
            mail: email
        });
        
        // 根据后端返回的数据判断邮箱是否已注册
        // 假设后端返回 { exists: true/false } 或者 { code: 200, data: { exists: true/false } }
        return { exists: response.data?.exists || response.exists || false };
    } catch (error) {
        // 返回错误信息，让调用方决定如何处理
        return { exists: false, error: error.message };
    }
}

export async function validateEmail(shadowRoot, component) {
    const emailInput = shadowRoot.getElementById('registerEmail');
    const emailError = shadowRoot.getElementById('registerEmailError');
    const email = emailInput.value;

    if (!email) {
        component.hideError(emailError);
        return true;
    }

    const emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
    if (!emailRegex.test(email)) {
        component.showError(emailError, '邮箱格式不正确，请及时更正');
        return false;
    }

    // 检测邮箱是否已经注册
    // 显示检测中状态
    emailError.textContent = '检测邮箱中...';
    emailError.classList.add('checking');
    emailError.classList.remove('show');
    emailError.style.color = '#6b7280';
    emailError.style.display = 'block';

    const result = await checkEmailExists(email);
    
    // 清除检测中状态
    emailError.classList.remove('checking');
    emailError.style.color = '';
    
    if (result.error) {
        // 检测过程中出现错误，显示错误信息
        component.showError(emailError, result.error);
        return false;
    } else if (result.exists) {
        // 邮箱已被注册
        component.showError(emailError, '该邮箱已被注册，请使用其他邮箱');
        return false;
    } else {
        // 邮箱可用，显示成功提示
        emailError.textContent = '邮箱可用';
        emailError.style.color = '#10b981';
        emailError.style.display = 'block';
        emailError.classList.remove('show');
        return true;
    }
}

export function validatePassword(shadowRoot, component) {
    const passwordInput = shadowRoot.getElementById('registerPassword');
    const confirmPasswordInput = shadowRoot.getElementById('registerConfirmPassword');
    const passwordError = shadowRoot.getElementById('registerPasswordError');
    const confirmPasswordError = shadowRoot.getElementById('registerConfirmPasswordError');
    
    const password = passwordInput.value;
    const confirmPassword = confirmPasswordInput.value;

    let isValid = true;

    // 验证密码
    if (password) {
        const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&.])[A-Za-z\d@$!%*#?&_.]{8,}$/;

        console.warn(password)
        if (!passwordRegex.test(password)) {
            component.showError(passwordError, '密码至少8位，必须包含字母和数字,和@$!%*#?&_.');
            isValid = false;
        } else {
            component.hideError(passwordError);
        }
    } else {
        component.hideError(passwordError);
    }

    // 验证确认密码
    if (confirmPassword && password !== confirmPassword) {
        component.showError(confirmPasswordError, '两次输入的密码不一致');
        isValid = false;
    } else if (confirmPassword) {
        component.hideError(confirmPasswordError);
    }

    return isValid;
}

export function showError(errorElement, message) {
    errorElement.textContent = message;
    errorElement.classList.add('show');
}

export function hideError(errorElement) {
    errorElement.classList.remove('show');
}

export function showSuccess(message, shadowRoot) {
    // 创建成功提示元素
    const successDiv = document.createElement('div');
    successDiv.className = 'success-message';
    successDiv.textContent = message;
    successDiv.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: #10b981;
        color: white;
        padding: 12px 24px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
        z-index: 10000;
        font-size: 14px;
        font-weight: 500;
        opacity: 0;
        transition: opacity 0.3s ease;
    `;

    document.body.appendChild(successDiv);

    // 显示动画
    setTimeout(() => {
        successDiv.style.opacity = '1';
    }, 10);

    // 自动移除
    setTimeout(() => {
        successDiv.style.opacity = '0';
        setTimeout(() => {
            if (successDiv.parentNode) {
                successDiv.parentNode.removeChild(successDiv);
            }
        }, 300);
    }, 3000);
}

export function clearErrors(shadowRoot) {
    const errorElements = shadowRoot.querySelectorAll('.error-message');
    errorElements.forEach(element => {
        element.classList.remove('show');
    });
}

export function resetForm(shadowRoot) {
    const form = shadowRoot.getElementById('registerForm');
    form.reset();
}

export function setLoading(loading, shadowRoot) {
    const registerBtn = shadowRoot.getElementById('registerBtn');
    const form = shadowRoot.getElementById('registerForm');
    
    if (loading) {
        registerBtn.loading = true;
        registerBtn.textContent = '注册中...';
        form.classList.add('loading');
    } else {
        registerBtn.loading = false;
        registerBtn.innerHTML = '<sl-icon name="person-plus" slot="prefix"></sl-icon>注册';
        form.classList.remove('loading');
    }
}